<template>
  <div class="users">
    <!-- 面包屑导航 -->
    <breadcrumb firstTitle="用户管理" secondTitle="用户列表"></breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserInfo">
            <el-button slot="append" icon="el-icon-search" @click="getUserInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialog=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表单区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 注意： mg_state是个布尔值  无法知道在页面中渲染出来 -->
        <el-table-column label="状态" prop="mg_state">
          <!-- 这里可以通过作用域插槽来获取当前行的数据 -->
          <!-- scope.row =>就是当前行的所有数据 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip content="编辑内容" placement="top" :enterable="false">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditorDialog(scope.row.id)"></el-button>
            </el-tooltip>

            <el-tooltip content="删除内容" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeleteMessageBox(scope.row.id)"></el-button>
            </el-tooltip>

            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" @click="showRole(scope.row)" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>

        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[1,2,5,10]" :page-size="queryInfo.pagesize" small layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户dialog对话框 -->
    <el-dialog title="提示" :visible.sync="addDialog" width="50%" @close="addFormClear">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" status-icon :rules="addFormRules" ref="ruleFormRef" label-width="70px">

        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model.number="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addFormUsers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户dialog对话框 -->
    <el-dialog title="修改用户" :visible.sync="editorDialog" width="50%" @close="editorDialogClear">
      <el-form :model="editorForm" :rules="editFormRules" ref="editorFormRef" label-width="70px">
        <el-form-item label="用户名:">
          <el-input v-model="editorForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editorForm.email"></el-input>
        </el-form-item>

        <el-form-item label="电话:" prop="mobile">
          <el-input v-model="editorForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorDialog = false">取 消</el-button>
        <el-button type="primary" @click="preTestEditor">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色dialog对话框 -->
    <el-dialog title="提示" :visible.sync="roleDialogVisible" width="50%" @close="closeRoleDialog">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择角色">
            <el-option v-for="item in roleRight" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="roleDialogVisible= false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '../../network/request'
import breadcrumb from '../breadcurmb/BreakCrumb.vue'
import { userAddFormMixin } from '../../common/mixin'

export default {
  name: 'MyUsers',
  mixins: [userAddFormMixin],
  data() {
    return {
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表
      userList: [],
      // 总数据条数
      total: 0,
      // 控制添加用户dialog对话框显示与隐藏
      addDialog: false,
      // 控制编辑dialog对话框的显示与隐藏
      editorDialog: false,

      // 控制编辑对话框的内容
      editorForm: {},
      // 控制分配角色dialog对话框是否隐藏
      roleDialogVisible: false,
      // 控制分配角色dialog对话框的内容
      userInfo: {},
      // 显示所有权限
      roleRight: [],
      // 保存选中下拉菜单的角色id值
      selectRoleId: ''
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 获取左侧菜单栏  用户列表数据
    async getUserInfo() {
      const { data: res } = await request({
        url: '/users',
        method: 'get',
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },

    // 更改页码 时触发 100 200 300 400
    handleSizeChange(newpage) {
      this.queryInfo.pagesize = newpage
      // 重新请求左侧菜单栏 用户列表数据
      this.getUserInfo()
    },
    // 更改当前页面1-100页面 触发
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page
      // 重新请求左侧菜单栏 用户列表数据
      this.getUserInfo()
    },
    // 保存switch开关的状态
    async changeState(val) {
      const { data: res } = await request.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 关闭dialog弹出框时情况form表单中的内容
    addFormClear() {
      this.$refs.ruleFormRef.resetFields()
    },
    // 在点击确定时先进行一次表达的预校验
    addFormUsers() {
      this.$refs.ruleFormRef.validate(async valid => {
        // 没有验证成功  不发送添加用户的网络请求
        if (!valid) return
        // 校验成功
        const { data: res } = await request.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('用户添加失败')
        this.$message.success('用户添加成功')
        // 隐藏添加的对话框
        this.addDialog = false
        // 重新获取表单数据
        this.getUserInfo()
      })
    },
    // 显示编辑用户对话框
    async showEditorDialog(id) {
      this.editorDialog = true
      const { data: res } = await request(`users/${id}`)
      if (res.meta.status !== 200) return
      this.editorForm = res.data
    },
    // 监听当编辑对话框隐藏时  清楚编辑对话框中form中表单的内容或者是操作
    editorDialogClear() {
      this.$refs.editorFormRef.resetFields()
    },
    // 对编辑对话框中的表单进行预校验 并更新用户列表
    preTestEditor() {
      this.$refs.editorFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await request.put(`users/${this.editorForm.id}`, {
          email: this.editorForm.email,
          mobile: this.editorForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('编辑用户信息失败')
        this.$message.success('编辑用户信息成功')

        // 刷新用户列表
        this.getUserInfo()
        this.editorDialog = false
      })
    },
    // 点击删除按钮  获取id  删除当前行的用户信息
    async showDeleteMessageBox(id) {
      const resultConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (resultConfirm !== 'confirm') {
        return this.$message.info('取消删除用户信息')
      }

      const { data: res } = await request.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户信息失败')
      }
      this.$message.success('删除用户信息成功！')

      // 重新获取页面数据
      this.getUserInfo()
    },
    // 展示分配角色的对话框
    async showRole(val) {
      this.userInfo = val
      this.roleDialogVisible = true

      const { data: res } = await request('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleRight = res.data
    },
    // 保存角色分配信息
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择角色')
      }
      const { data: res } = await request.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败！')
      }

      this.$message.success('更新角色成功！')
      // 重新渲染用户列表权限
      this.getUserInfo()
      this.roleDialogVisible = false
    },
    // 关闭分配角色对话框  然后清除下拉菜单
    closeRoleDialog() {
      this.selectRoleId = ''
      this.userInfo = {}
    }

  },
  components: {
    breadcrumb
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 15px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>